/*
Copyright 2022.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1

import (
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"fmt"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// EDIT THIS FILE!  THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required.  Any new fields you add must have json tags for the fields to be serialized.

// TriggerInstanceSpec defines the desired state of TriggerInstance
// +k8s:deepcopy-gen=false
type TriggerInstanceSpec struct {
	// INSERT ADDITIONAL SPEC FIELDS - desired state of cluster
	// Important: Run "make" to regenerate code after modifying this file
	// +kubebuilder:pruning:PreserveUnknownFields
	Data    string                 `json:"data,omitempty"`
	DataObj map[string]interface{} `json:"-"`
}

// TriggerInstanceStatus defines the observed state of TriggerInstance
type TriggerInstanceStatus struct {
	// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
	// Important: Run "make" to regenerate code after modifying this file
	ResourceStatus []ResourceStatus `json:"resourcestatus"`
}

//+kubebuilder:object:root=true
//+kubebuilder:subresource:status

// TriggerInstance is the Schema for the triggerinstances API
type TriggerInstance struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec   TriggerInstanceSpec   `json:"spec,omitempty"`
	Status TriggerInstanceStatus `json:"status,omitempty"`
}

//+kubebuilder:object:root=true

// TriggerInstanceList contains a list of TriggerInstance
type TriggerInstanceList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []TriggerInstance `json:"items"`
}

func init() {
	SchemeBuilder.Register(&TriggerInstance{}, &TriggerInstanceList{})
}

func (in *TriggerInstance) UpdateResourceStatus(name string, message string, phase string, status string, kind string, version string) {
	notFound := true
	for i := 0; i < len(in.Status.ResourceStatus); i++ {
		if in.Status.ResourceStatus[i].Name == name && in.Status.ResourceStatus[i].Kind == kind {
			notFound = false
			in.Status.ResourceStatus[i].Status = status
			in.Status.ResourceStatus[i].Message = message
			in.Status.ResourceStatus[i].Phase = phase
		}
	}
	if notFound {
		in.Status.ResourceStatus = append(in.Status.ResourceStatus, ResourceStatus{
			Name:       name,
			Kind:       kind,
			ApiVersion: version,
			Message:    message,
			Phase:      phase,
			Status:     status,
		})
	}
}

func (in *TriggerInstance) GetNamespacedName() string {
	return fmt.Sprintf("%s/%s", in.Namespace, in.Name)
}

func (in *TriggerInstance) GetStatusHash() string {
	status, err := json.Marshal(in.Status)
	if err != nil {
		return ""
	}
	h := sha1.New()
	h.Write(status)
	return hex.EncodeToString(h.Sum(nil))
}

func (in *TriggerInstanceSpec) DeepCopyInto(out *TriggerInstanceSpec) {
	*out = *in
}
